# curl 'https://baijiahao.baidu.com/s?id=1694180799013112340&wfr=spider&for=pc' > index.html
# git clone https://gitee.com/Farmer-chong/simple-http-server.git
systemLanguage=($(locale | grep LANG | sed s/'LANG='// | tr -d '"' | cut -d "." -f 1))
downloadHost="https://gitee.com/Farmer-chong/simple-http-server.git"
hasFiglet=($(which figlet | wc -l))
hasGit=($(which git | wc -l))
sysIsCentos=($(which yum | wc -l))

if [[ "${hasFiglet}" != "1" && "${hasGit}" == "1" ]]
then
    echo "安装依赖..."
    if [[ "${sysIsCentos}" == "1" ]]
    then
        echo "Your System is Centos."
        echo "更新软件源..."
        sudo yum install -y epel-release
        sudo yum update
        sudo yum install figlet git -y
    else
        echo "Your System is Ubuntu"
        sudo apt update
        sudo apt install figlet git -y
    fi
else
    echo "依赖已安装"
fi

cat << EEF
    (1) 启动服务器
    (2) 清除服务器
EEF
read -p "请选择操作方式" isStart

if [[ "${isStart}" == "2" ]]
then
    total=($(ps -aux | grep server.py | wc -l))
    if [[ "${total}" == "1" ]]
    then
        echo "服务器未启动"
    else
        ps ux | grep -E 'server.py' | grep -v grep |awk '{print $2}' |xargs kill
    fi
    exit
fi

if [[ "${systemLanguage}" == "zh_CN" ]]
then
    read -p "请选择服务器是否后台启动(Y/N):" isNohup
else
    read -p 'Please select whether the server starts in the background(Y/N):' isNohup
fi

function isZhCN(){
    if [[ "$systemLanguage" == "zh_CN" ]]
    then
        echo "1"
    else
        echo "0"
    fi
}

if [[ "${systemLanguage}" == "zh_CN" ]]
then
    echo "欢迎使用FSS"
else
    echo "Welcome use FSS"
fi

if [ -d simple-http-server ]
then
    if [[ $(isZhCN $systemLanguage) == '1' ]]
    then
        echo "简易http服务器已存在"
    else
        echo 'Simple server exits.'
    fi
    cd simple-http-server
    git pull
else
    echo "downloading simple-http-server"
    git clone ${downloadHost}
    cd simple-http-server
    sudo pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt
fi


# 获取前端页面
# http://linux.farmer233.top/dist.tar.gz
if [ -d dist ]
then
    echo "前端页面已部署"
else
    wget http://linux.farmer233.top/dist.tar.gz
    tar -xvf dist.tar.gz
fi

# 读取环境变量
varb=`cat .env | xargs echo`
# 设置环境变量
export $varb

echo "Socket Server" | figlet
# 启动服务器
if [[ "${isNohup}" == 'Y' ]]
then
    nohup python3 server.py > /dev/null &
else
    python3 server.py
fi


# 命令数量: if export function echo pip git python3 figlet 管道符|
# locale grep sed LANG tr cut read cat EEF 导流符(> >> < <<)
# wc ps xargs kill awk wget tar apt yum uname which
# 30 nums